var express = require('express');
const mongoose=require('mongoose')
const db=require('../mongodb/db');
const multer=require('multer')
const qr = require('qr-image');
const util = require('util');
const Buffer = require('buffer').Buffer;
const applymodel = require('../mongodb/models/apply');
const usermodel=require('../mongodb/models/usermodel')
var router = express.Router();


/* profile */
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/upload/');
  },
  filename: function (req, file, cb) {
    cb(null, `${Date.now()}-${file.originalname}`);
  }
});

const upload = multer({ storage });
/* ---- */


/* qrcode */
function bufferToDataURL(buffer, mimeType = 'image/png') {
  const dataURLPrefix = `data:${mimeType};base64,`;
  const base64Data = buffer.toString('base64');
  return dataURLPrefix + base64Data;
}

function generateQRCode(id) {
  const qrBuffer = qr.imageSync(id, { type: 'png' });
  return bufferToDataURL(qrBuffer);
}
/* qr */

db(()=>{

})


let middle = (req, res, next) => {
  if (!req.session.username) {
      res.redirect('/login')
  }

  next()
}
 let prehome=(req,res,next)=>{
  if(req.session.ifapply){
     res.redirect('/home')
     return
  }
  next()
} 

let home=(req,res,next)=>{
  if(req.session.ifapply){
    next()
    return
  }
  else{
    return res.redirect('/prehome')

  }
}
 let apply=(req,res,next)=>{
  if(req.session.ifapply){
     res.redirect('/applyshow')
     return
  }
  next()
} 

let applyshow=(req,res,next)=>{
  if(req.session.ifapply){
    next()
    return
  }
  else{
    return res.redirect('/apply')

  }
}
/* GET home page. */
router.get('/', function(req, res, next) {
  if(req.session.ifapply){
    res.redirect('/home')
    return
  }
  else{
    res.redirect('/prehome')
    return
  }
  return
});

router.get('/apply', middle,apply, function(req, res, next) {
    res.render('apply')
  return
});
router.get('/prehome', middle,prehome,function(req, res, next) {
  res.render('prehome')
  return
});
router.get('/home', middle,home,function(req, res, next) {
  res.render('home')
  return
});




router.get('/applyshow', middle, applyshow,function (req, res, next) {
  applymodel.findOne({ uid: req.session._id }, (err, data) => {
    if (err) {
      return console.log(err)
    }
    res.render('applyshow',{show:data})
   

  })

  return
}); 



router.post('/apply',upload.fields([
  {name:'avatar',maxCount:1},
  {name:'one',maxCount:1},
  {name:'two',maxCount:1},
  {name:'three',maxCount:1},
]), middle,function(req, res, next) {
  const qrCodeDataUrl = generateQRCode(req.session._id);
  let avatarFilename = req.files && req.files.avatar && req.files.avatar.length > 0 ? req.files['avatar'][0].filename : '1708437536082-profile.jpg';
  let oneFilename = req.files && req.files.one && req.files.one.length > 0 ? req.files['one'][0].filename : '1708437536083-work.jpg';
  let twoFilename = req.files && req.files.two && req.files.two.length > 0 ? req.files['two'][0].filename : '1708437536083-work.jpg';
  let threeFilename = req.files && req.files.three && req.files.three.length > 0 ? req.files['three'][0].filename : '1708437536083-work.jpg';

  let applydata={
    qrcode: qrCodeDataUrl,
    uid:req.session._id,
    avatar: avatarFilename,
    name:req.body.name,
    gender: req.body.gender,
    college: req.body.college,
    major: req.body.major,
    number: req.body.number,
    first: req.body.first,
    second: req.body.second,
    way: req.body.way,
    remark: req.body.remark,
    one: oneFilename,
    two: twoFilename,
    three: threeFilename,
  }

  applymodel.create(applydata,(err,data)=>{
    if(err){
      console.log(err)
    }
    usermodel.updateOne({_id:req.session._id},{ifapply:true},(err,data)=>{
      if(err){
        console.log('更新失败')
        return
      }
    })
    req.session.ifapply = true
    req.session.name=req.body.name
    res.redirect('/applyshow')
  })
  return
});

 router.get('/applychange',middle,applyshow,(req,res,next)=>{
    applymodel.findOne({uid:req.session._id},(err,data)=>{
      if(err){
        return console.log(err)
      }
      res.render('applychange',{change:data})
    })

 })

router.post('/applychange', upload.fields([
  { name: 'avatar', maxCount: 1 },
  { name: 'one', maxCount: 1 },
  { name: 'two', maxCount: 1 },
  { name: 'three', maxCount: 1 },
]), middle,async(req,res,next)=>{
  try {
    let data = await applymodel.findOne({ uid: req.session._id });

    let avatarFilename = req.files && req.files.avatar && req.files.avatar.length > 0 ? req.files['avatar'][0].filename : data.avatar;
    let oneFilename = req.files && req.files.one && req.files.one.length > 0 ? req.files['one'][0].filename : data.one;
    let twoFilename = req.files && req.files.two && req.files.two.length > 0 ? req.files['two'][0].filename : data.two;
    let threeFilename = req.files && req.files.three && req.files.three.length > 0 ? req.files['three'][0].filename : data.three;

    let changedata = {
      avatar: avatarFilename,
      name: req.body.name,
      gender: req.body.gender,
      college: req.body.college,
      major: req.body.major,
      number: req.body.number,
      first: req.body.first,
      second: req.body.second,
      remark: req.body.remark,
      one: oneFilename,
      two: twoFilename,
      three: threeFilename,
    };

    await applymodel.updateOne({ uid: req.session._id }, changedata);
    res.redirect('/applyshow');
  } catch (err) {
    console.log('修改失败:', err);
    res.status(500).send('服务器错误');
  }
});

 router.get('/out',middle,(req,res,next)=>{
    res.render('logout')
    return 

 })



 /* 面试结果 */
/* let ifpass=(req,res,next)=>{
  usermodel.findOne({uid:req.session._id},(err,data)=>{
    if(err){
      return console.log(err)
    }
    req.session.ifpass= data.ifpass
  })
  applymodel.findOne({uid:req.session._id},(err,data)=>{
    if(err){
      return console.log(err)
    }
     req.session.name = data.name
  })
  let code=req.session.ifpass
  let name=req.session.name
  console.log(code)
  console.log(name)
  if(code==='0'){
    res.render('res0',{name:name})
    return
  }
  else if(code==='1'){
    res.render('res1')
    return 
  }
  else if(code==='2'){
    res.render('res2')
    return
  }
  next()
} */
 router.get('/result',middle,home,(req,res,next)=>{
   usermodel.findOne({ _id: req.session._id }, (err, data) => {
     if (err) {
       return console.log(err)
     }
     if (data.ifpass === '0') {
       res.render('res0')
       return
     }
     else if (data.ifpass === '1') {
       res.render('res1', { name: req.session.name })
       return
     }
     else if (data.ifpass === '2') {
       res.render('res2', { name: req.session.name })
       return
     }
     else if (data.ifpass === '3') {
       res.render('res3', { name: req.session.name })
       return
     }
     else if (data.ifpass === '4') {
       res.render('res4')
       return
     }
     
   })
   

 })

 router.get('/qrcode',(req,res,next)=>{
    applymodel.findOne({uid:req.session._id},(err,data)=>{
      if(err){
        console.log(err)
        return 
      }
      res.render('qr',{url:data})
    })
 })
module.exports = router;
